package dhm.com.hpx.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.hpx.R;
import dhm.com.hpx.base.BaseActivity;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.Bean;
import dhm.com.hpx.entity.GetUserInfoBean;
import dhm.com.hpx.entity.HeaderIMage;
import dhm.com.hpx.entity.Province;
import dhm.com.hpx.utils.BitmapUtil;
import dhm.com.hpx.utils.GetJsonDataUtil;
import dhm.com.hpx.utils.HeaderImageCallback;
import dhm.com.hpx.utils.SpUtils;
import dhm.com.hpx.utils.TakePhotoUtil;
import okhttp3.Call;

public class MyinfoActivity extends BaseActivity implements LoginContract.IView {

    @BindView(R.id.headImage)
    SimpleDraweeView headImage;
    @BindView(R.id.nick)
    TextView nick;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.edit_wechat)
    EditText editWechat;
    @BindView(R.id.edit_job)
    EditText editJob;
    @BindView(R.id.edit_addr)
    TextView editAddr;
    @BindView(R.id.edit_introduce)
    EditText editIntroduce;
    @BindView(R.id.edit_work)
    EditText editWork;
    @BindView(R.id.edit_company)
    EditText editCompany;
    private PressenterImpl pressenter;
    private String uid;

    private OptionsPickerView pvOptions;

    private List<String> sexlist = new ArrayList<>();

    private String province;
    private String city;
    private String area;


    @Override
    protected int getLayout() {
        return R.layout.activity_myinfo;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        pressenter = new PressenterImpl();
        pressenter.attachView(this);
        sexlist.clear();
        sexlist.add("拍照");
        sexlist.add("相册");

        uid = SpUtils.getString(this, "uid");

        initJsonData();

     /*   nick.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String s = nick.getText().toString();
                if (s==null||s.equals("")){
                    return;
                }
                if (s.length()>6){
                    Toast.makeText(MyinfoActivity.this, "最多输入6个字呦", Toast.LENGTH_SHORT).show();
                    nick.setText(s.substring(0,6));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        editPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String s = editPhone.getText().toString();
                if (s==null||s.equals("")){
                    return;
                }
                if (s.length()>11){
                    Toast.makeText(MyinfoActivity.this, "最多输入11个数字呦", Toast.LENGTH_SHORT).show();
                    editPhone.setText(s.substring(0,11));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        editJob.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String s = editJob.getText().toString();
                if (s==null||s.equals("")){
                    return;
                }
                if (s.length()>11){
                    Toast.makeText(MyinfoActivity.this, "最多输入11个数字呦", Toast.LENGTH_SHORT).show();
                    editJob.setText(s.substring(0,11));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        editIntroduce.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String s = editIntroduce.getText().toString();
                if (s==null||s.equals("")){
                    return;
                }
                if (s.length()>6){
                    Toast.makeText(MyinfoActivity.this, "最多输入15个字呦", Toast.LENGTH_SHORT).show();
                    editIntroduce.setText(s.substring(0,15));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        editWork.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String s = editWork.getText().toString();
                if (s==null||s.equals("")){
                    return;
                }
                if (s.length()>6){
                    Toast.makeText(MyinfoActivity.this, "最多输入8个字呦", Toast.LENGTH_SHORT).show();
                    editWork.setText(s.substring(0,8));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        editCompany.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String s = editCompany.getText().toString();
                if (s==null||s.equals("")){
                    return;
                }
                if (s.length()>6){
                    Toast.makeText(MyinfoActivity.this, "最多输入8个字呦", Toast.LENGTH_SHORT).show();
                    editCompany.setText(s.substring(0,8));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });*/

    }

    @Override
    protected void initData() {
        Map<String, String> map = new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("uid", uid);
        pressenter.sendMessage(this, Constant.get_userinfo, map, GetUserInfoBean.class);
    }

    @Override
    public void requesta(Object data) {
        if (data instanceof GetUserInfoBean) {
            GetUserInfoBean getUserInfoBean = (GetUserInfoBean) data;
            if (getUserInfoBean.getCode() == 1) {
                headImage.setImageURI(Constant.PATH+"/"+getUserInfoBean.getData().getHeadsmall());
                nick.setText(getUserInfoBean.getData().getUser_nickname());
                editPhone.setText(getUserInfoBean.getData().getMobile());
                editCompany.setText(getUserInfoBean.getData().getCompany());
                editIntroduce.setText(getUserInfoBean.getData().getIntro());
                editJob.setText(getUserInfoBean.getData().getOccupation());
                editWechat.setText(getUserInfoBean.getData().getUserQQ());
                editWork.setText(getUserInfoBean.getData().getBusiness());
                if (getUserInfoBean.getData().getProvince()!=null&&!getUserInfoBean.getData().getProvince().equals("null")){
                    province=getUserInfoBean.getData().getProvince();
                    city=getUserInfoBean.getData().getCity();
                    area=getUserInfoBean.getData().getArea();
                    editAddr.setText(getUserInfoBean.getData().getProvince()+getUserInfoBean.getData().getArea()+getUserInfoBean.getData().getArea());
                }

            }
        }else if (data instanceof Bean){
            Bean bean= (Bean) data;
            if (bean.getCode()==1){
                Toast.makeText(this, bean.getMessage(), Toast.LENGTH_SHORT).show();
                finish();
            }else {
                Toast.makeText(this,"您未更改数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void fail(String error) {

    }
    private static final int TAKE_PICTURE = 0;
    private static final int IMAGE = 1;
    private static final int REQUEST_CODE_ASK_PERMISSIONS = 2;


    @OnClick({R.id.back, R.id.image, R.id.yinsi, R.id.ohone, R.id.wechat, R.id.job, R.id.addr, R.id.introduce, R.id.work, R.id.company, R.id.sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.image:
            //选择地址
                pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        if (options1==0){
                            //拍照
                            takePhotoClick();

                        }else {
                            //相册
                            choose_photo_layout_click();

                        }
                    }
                }).build();
                //三级选择器
                pvOptions.setPicker(sexlist);
                pvOptions.show();
                break;
            case R.id.sure:
                String user_nickname = nick.getText().toString();
                String mobile = editPhone.getText().toString();
                String userQQ = editWechat.getText().toString();
                String occupation = editJob.getText().toString();
                String intro = editIntroduce.getText().toString();
                String business = editWork.getText().toString();
                String company = editCompany.getText().toString();
/*
                if (user_nickname==null||user_nickname.equals("")||mobile==null||mobile.equals("")||userQQ==null||userQQ.equals("")||occupation==null||occupation.equals("")||
                        intro==null||intro.equals("")||business==null||business.equals("")||company==null||company.equals("")||province==null||province.equals("")||
                        city==null||city.equals("")||area==null||area.equals("")){
                    Toast.makeText(this, "请检查数据", Toast.LENGTH_SHORT).show();
                    return;
                }
*/
                Map<String,String> map=new HashMap<>();
                map.put("token",Constant.TOKEN);
                map.put("uid",uid);
                map.put("user_nickname",user_nickname);
                map.put("mobile",mobile);
                map.put("userQQ",userQQ);
                map.put("occupation",occupation);
                map.put("intro",intro);
                map.put("business",business);
                map.put("company",company);
                map.put("province",province);
                map.put("city",city);
                map.put("area",area);


                pressenter.sendMessage(this,Constant.update_info,map, Bean.class);



                break;
            case R.id.yinsi:
                break;
            case R.id.ohone:
                break;
            case R.id.wechat:
                break;
            case R.id.job:
                break;
            case R.id.addr:

                //选择地址
                pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        editAddr.setText(options1Items.get(options1).getPickerViewText()
                                + options2Items.get(options1).get(options2)
                                + options3Items.get(options1).get(options2).get(options3));
                        province=options1Items.get(options1).getPickerViewText();
                        city=options2Items.get(options1).get(options2);
                        area=options3Items.get(options1).get(options2).get(options3);
                    }
                }).build();

                pvOptions.setPicker(optionshItems, options2Items, options3Items);//三级选择器
                pvOptions.show();
                break;
            case R.id.introduce:
                break;
            case R.id.work:
                break;
            case R.id.company:
                break;
                default:
        }
    }

    /**
    拍照
    */
    void takePhotoClick() {
        if (Build.VERSION.SDK_INT >= 23) {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_ASK_PERMISSIONS);
        } else {
            startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
        }
    }

    /**
     选取相册图片
     * */
    void choose_photo_layout_click() {
        //调用相册
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, IMAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
                } else {
                    // 没有打开相机的权限
                    Toast.makeText(this, "没有打开照相机权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK && null != data) {
            String sdState = Environment.getExternalStorageState();
            if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                return;
            }
            String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
            Bundle bundle = data.getExtras();
            //获取相机返回的数据，并转换为图片格式
            Bitmap bitmap = (Bitmap) bundle.get("data");
            FileOutputStream fout = null;
            File file = new File("/sdcard/pics/");
            file.mkdirs();
            String filename = file.getPath() + name;
            try {
                fout = new FileOutputStream(filename);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fout);
                showImage(filename);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    fout.flush();
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //显示图片
        }else if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            //获取图片路径
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String imagePath = c.getString(columnIndex);
            showImage(imagePath);
            c.close();
        }
    }

    //加载图片
    private void showImage(String imaePath){
        Bitmap bm = BitmapFactory.decodeFile(imaePath);
        String url = TakePhotoUtil.saveTodisk(bm, Constant.HeadPath);
        headImage.setImageBitmap(bm);
        uploadImage(url);
    }

    private void uploadImage(final String url) {
        OkHttpUtils.post().url(Constant.PATH + Constant.modify_headsmall)
                .addFile("image", url, new File(bitmapToString(BitmapUtil.getimage(url))))
                .addParams("uid", uid)
                .addParams("token", Constant.TOKEN)
                .build().execute(new HeaderImageCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(HeaderIMage response, int id) {
                if (response != null && response.getCode() == 1) {
                    initData();
                    Toast.makeText(MyinfoActivity.this, response.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    public String bitmapToString(Bitmap bitmap) {
        //将bitmap转换为uri
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null));
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor.getString(actual_image_column_index);
        return img_path;
    }


    public ArrayList<Province> parseData(String result) {//Gson 解析
        ArrayList<Province> detail = new ArrayList<>();
        detail.clear();
        Gson gson = new GsonBuilder().setLenient().create();
        detail = gson.fromJson(result, new TypeToken<List<Province>>() {
        }.getType());

        return detail;
    }

    private ArrayList<Province> options1Items = new ArrayList<>(); //省
    private ArrayList<String> optionshItems = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();//市
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();//区

    private void initJsonData() {
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<Province> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            optionshItems.add(jsonBean.get(i).getName());

            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三级）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }




}
